<template>
	<view class="customer-page">
		<!-- 搜索区域 -->
		<view class="search-section">
			<uni-easyinput v-model="searchKeyword" placeholder="请输入客户姓名或手机号" placeholder-style="color: #999"
				@confirm="onSearch" @input="onSearchInput" clearable>
				<template #right>
					<uni-icons type="search" size="18" color="#999" @click="onSearch" />
				</template>
			</uni-easyinput>
		</view>

		<!-- 筛选区域 -->
		<!-- <view class="filter-section">
      <view class="filter-item">
        <text class="filter-label">选择日期</text>
        <uni-datetime-picker 
          v-model="range" 
          type="daterange" 
          @change="onDateChange"
        />
      </view>
      <view class="filter-item" @click="openStatusPicker">
        <text class="filter-label">报名状态</text>
        <text class="filter-value">
          {{ getStatusLabel(selectedStatus) }}
        </text>
        <uni-icons type="arrowdown" size="14" color="#666" />
      </view>
    </view> -->

		<!-- 选项卡 -->
		<view class="tab-section">
			<scroll-view class="tab-scroll" scroll-x>
				<view class="tab-container">
					<view class="tab-item" v-for="(tab, index) in tabs" :key="index"
						:class="{ active: activeTabIndex === index }" @click="switchTab(index)">
						<text class="tab-text">{{ tab.label }}({{ tab.count || 0 }})</text>
						<view class="tab-line" v-if="activeTabIndex === index"></view>
					</view>
				</view>
			</scroll-view>
		</view>

		<!-- 客户列表 -->
		<swiper class="content-swiper" id="content" :current="activeTabIndex" @change="onSwiperChange"
			:style="{height:height}" :duration="300">
			<swiper-item v-for="(tab, index) in tabs" :key="index">
				<scroll-view :style="{height:height}" class="customer-list" scroll-y @scrolltolower="onReachBottomFun"
					refresher-enabled @refresherrefresh="onRefresh" :refresher-triggered="refreshing">
					<view class="list-container">
						<!-- 空状态 -->
						<view class="empty-state"
							v-if="!getCurrentTabData().loading && getCurrentTabData().list.length === 0">
							<image src="/static/images/empty.png" class="empty-image" />
							<text class="empty-text">暂无客户数据</text>
						</view>

						<!-- 客户列表 -->
						<view v-for="customer in getCurrentTabData().list" :key="customer._id" class="customer-item"
							@tap.stop="viewCustomer(customer)">
							<view class="customer-header">
								<view class="customer-name-phone">
									<text class="customer-name">{{ customer.customerName || '未知客户' }}</text>
									<text class="customer-phone">{{ formatPhone(customer.phone) }}</text>

									<text class="customer-phone"
										v-if="customer.scheduleDateTime">上次报备:{{ $formatTime(customer.scheduleDateTime) }}</text>
								</view>
								<view class="customer-time">
									{{ formatTime(customer.createTime) }}
								</view>
							</view>

							<!-- 状态标签 -->
							<view class="status-tags">
								<view v-for="tag in getStatusTags(customer)" :key="tag.text" class="status-tag"
									:class="tag.type">
									{{ tag.text }}
								</view>

							</view>
							<template>
								<view class="action-buttons">
									<view class="btn-small primary" v-if="customer.isSchedule === 0 && customer.status !='cancel'" @tap.stop="scheduleVisit(customer)">报备</view>
									<!-- <view class="btn-small primary" v-if="customer.isSchedule === 0 && customer.status !='cancel'" @tap.stop="scheduleVisit(customer)">联系</view> -->
									<view class="btn-small secondary" 	v-if="customer.isSchedule === 1 && customer.status !='cancel' && customer.scheduleNo" @tap.stop="showQrcode(customer)">报备码</view>
								</view>
								<!-- <view class="status-tags">
								<view class="status-tag primary"
									v-if="customer.isSchedule === 0 && customer.status !='cancel'">
									报备
								</view>
								<view class="status-tag success"
									v-if="customer.isSchedule === 1 && customer.status !='cancel' && customer.scheduleNo"
									@tap.stop="showQrcode(customer)">报备码</view>
								</view> -->
							</template>

							<!-- 说明信息 -->
							<view v-if="customer.remark" class="remark-section">
								<text class="remark-label">备注：</text>
								<text class="remark-text">{{ customer.remark }}</text>
							</view>

							<!-- 带看人信息 -->
							<view v-if="customer.zhongjieYWYName" class="agent-info">
								<text class="agent-label">带看人：</text>
								<text class="agent-name">{{ customer.zhongjieYWYName }}</text>
								<text class="agent-phone">{{ customer.zhongjieYWYPhone }}</text>
								<text class="agent-shop">{{ customer.zhongjieYWYShop }}</text>
							</view>


						</view>
					</view>

					<!-- 加载状态 -->
					<view class="load-status">
						<view class="loading-more"
							v-if="getCurrentTabData().loading && getCurrentTabData().list.length > 0">
							<uni-load-more status="loading" content="正在加载..." />
						</view>
						<view class="no-more"
							v-else-if="!getCurrentTabData().hasMore && getCurrentTabData().list.length > 0">
							<uni-load-more status="noMore" content="没有更多数据了" />
						</view>
					</view>
				</scroll-view>
			</swiper-item>
		</swiper>

		<!-- 状态选择弹窗 -->

		<uni-popup ref="qrcode">
			<view class="qr-container">
				<view class="qrcode-area">
					<canvas canvas-id="myQrcode" style="width: 250px; height: 250px;"></canvas>
				</view>
				<view class="action-area">
					<button class="btn-small2 btn-primary" @click="saveQRCode">保存二维码</button>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import UQRCode from 'uqrcodejs';
	export default {
		data() {
			return {
				searchKeyword: '',
				activeTabIndex: 0,
				range: [],
				tabs: [{
						label: '全部',
						value: 'all',
						count: 0
					},
					{
						label: '报备',
						value: 'scheduled',
						count: 0
					},
					{
						label: '未报备',
						value: 'visited',
						count: 0
					},
					{
						label: '无效',
						value: 'cancell',
						count: 0
					},
					{
						label: '有效',
						value: 'customer',
						count: 0
					},
					// {
					// 	label: '认购',
					// 	value: 'rengou',
					// 	count: 0
					// },{
					// 	label: '签约',
					// 	value: 'qianyue',
					// 	count: 0
					// }
				],
				selectedStatus: '',
				refreshing: false,

				// 客户列表数据 - 为每个选项卡独立维护
				tabData: {
					'all': {
						list: [],
						page: 1,
						hasMore: true,
						loading: false
					},
					'scheduled': {
						list: [],
						page: 1,
						hasMore: true,
						loading: false
					},
					'visited': {
						list: [],
						page: 1,
						hasMore: true,
						loading: false
					},
					'cancell': {
						list: [],
						page: 1,
						hasMore: true,
						loading: false
					},
					'customer': {
						list: [],
						page: 1,
						hasMore: true,
						loading: false
					},
					// 'cancell': {
					// 	list: [],
					// 	page: 1,
					// 	hasMore: true,
					// 	loading: false
					// },
					// 'cancell': {
					// 	list: [],
					// 	page: 1,
					// 	hasMore: true,
					// 	loading: false
					// }
				},
				pageSize: 10,

				// 筛选选项
				statusOptions: [{
						label: '全部',
						value: ''
					},
					{
						label: '已报备',
						value: 'scheduled'
					},
					{
						label: '未报备',
						value: 'visited'
					},
					{
						label: '已取消',
						value: 'cancell'
					}
				],

				// 防抖定时器
				searchTimer: null,
				height: '500px'
			}
		},

		computed: {
			activeTab() {
				return this.tabs[this.activeTabIndex].value
			}
		},

		onLoad(query) {
			if(query.type){
				this.activeTabIndex = query.type*1
				this.$nextTick(()=>{
					this.loadCustomerList()
				})
			}
			this.$nextTick(()=>{
				this.loadCustomerList()
			})
			
		},

		onPullDownRefresh() {
			this.onRefresh()
		},
		mounted() {
			this.$nextTick(function() {
				setTimeout(() => {
					uni.getSystemInfo({
						success: (resu) => {
							const query = uni.createSelectorQuery()
							query.select('#content').boundingClientRect()
							query.exec(res => {
								console.log(res)
								console.log('resu.windowHeight', resu.windowHeight)
								this.height = resu.windowHeight - res[0].top - 1 +
								'px';

								console.log('this.height', this.height)
							})
						},
						fail: (res) => {}
					})
				}, 100)
			})
		},

		methods: {
			// 获取当前选项卡的数据
			getCurrentTabData() {
				return this.tabData[this.activeTab]
			},

			// 搜索客户 - 带防抖
			onSearchInput() {
				clearTimeout(this.searchTimer)
				this.searchTimer = setTimeout(() => {
					this.onSearch()
				}, 500)
			},

			onSearch() {
				this.resetAllTabs()
				this.loadCustomerList()
			},

			// 切换选项卡
			switchTab(index) {
				if (this.activeTabIndex === index) return

				this.activeTabIndex = index

				// 如果当前选项卡还没有数据，则加载数据
				const currentTabData = this.getCurrentTabData()
				if (currentTabData.list.length === 0 && !currentTabData.loading) {
					this.loadCustomerList()
				}
			},

			// swiper切换事件
			onSwiperChange(e) {
				const newIndex = e.detail.current
				if (this.activeTabIndex === newIndex) return

				this.activeTabIndex = newIndex

				// 如果当前选项卡还没有数据，则加载数据
				const currentTabData = this.getCurrentTabData()
				if (currentTabData.list.length === 0 && !currentTabData.loading) {
					this.loadCustomerList()
				}
			},

			// 日期选择
			onDateChange(e) {
				this.range = e
				this.resetAllTabs()
				this.loadCustomerList()
			},

			// 打开状态选择器
			openStatusPicker() {
				this.$refs.statusPopup.open()
			},

			// 选择状态
			selectStatus(status) {
				this.selectedStatus = status
				this.closeStatusPicker()
				this.resetAllTabs()
				this.loadCustomerList()
			},

			// 关闭状态选择器
			closeStatusPicker() {
				this.$refs.statusPopup.close()
			},

			// 获取状态标签文本
			getStatusLabel(status) {
				const option = this.statusOptions.find(opt => opt.value === status)
				return option ? option.label : '全部'
			},

			// 刷新数据
			onRefresh() {
				this.refreshing = true
				this.resetAllTabs()
				this.loadCustomerList().finally(() => {
					this.refreshing = false
					uni.stopPullDownRefresh()
				})
			},

			// 重置所有选项卡数据
			resetAllTabs() {
				Object.keys(this.tabData).forEach(key => {
					this.tabData[key].page = 1
					this.tabData[key].hasMore = true
					this.tabData[key].list = []
				})
				// 重置选项卡计数
				this.tabs.forEach(tab => {
					tab.count = 0
				})
			},

			// 加载更多数据
			onReachBottomFun() {
				const currentTabData = this.getCurrentTabData()
				if (currentTabData.hasMore && !currentTabData.loading) {
					currentTabData.page++
					this.loadCustomerList(true)
				}
			},
			async scheduleVisit(customer) {
				let curTime = this.$formatYear(new Date())
				await this.$cloudOBjAjax('customer-lifecycle-history', 'addZJSchedule', {
					customerId: customer._id,
					schedule_time: curTime
				}).then(res => {
					customer.isSchedule = 1
				})
			},

			// 加载客户列表
			async loadCustomerList(isLoadMore = false) {
				const currentTabData = this.getCurrentTabData()

				if (currentTabData.loading) return

				// 如果是加载更多且没有更多数据，直接返回
				if (isLoadMore && !currentTabData.hasMore) return

				currentTabData.loading = true

				try {
					// 构建查询条件
					let query = {
						page: currentTabData.page,
						pageSize: this.pageSize,

					}
					const role = this.$userInfo.role

					if (role === 4 || role === 5) {
						query.middlemanId = this.$userInfo._id
					}

					if (role == 3) {
						query.advisorId = this.$userInfo._id
					}
					const activeTabIndex = this.activeTabIndex
					switch (activeTabIndex) {
						case 1:
							query.isSchedule = 1
							break;
						case 2:
							query.isSchedule = 0
							break;
						case 3:
							query.status = 'cancel'
						case 4:
							query.bindCustomId = 'all'
						default:
							break;
					}

					// 搜索条件
					if (this.searchKeyword) {
						query.keyword = this.searchKeyword
					}

					// 日期范围条件
					if (this.range && this.range.length === 2) {
						query.startDate = this.range[0]
						query.endDate = this.range[1]
					}

					// 状态筛选条件
					if (this.selectedStatus) {
						query.status = this.selectedStatus
					}

					// 根据选项卡设置不同的状态筛选
					if (this.activeTab !== 'all') {
						query.tabStatus = this.activeTab
					}

					const res = await this.$cloudOBjAjax('middleman-advisor-customers', 'getCustomerList', query)

					const {
						list,
						total,
						hasNext
					} = res

					if (isLoadMore) {
						currentTabData.list = [...currentTabData.list, ...list]
					} else {
						currentTabData.list = list
					}
					currentTabData.hasMore = hasNext

					this.tabs[activeTabIndex].count = total
					// 更新选项卡计数

				} catch (error) {
					console.error('加载客户列表失败:', error)
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					})
					// 开发环境使用模拟数据

				} finally {
					currentTabData.loading = false
				}
			},


			// 获取状态标签
			getStatusTags(customer) {
				const tags = []

				// 根据客户状态添加标签
				if (customer.isSchedule === 1) {
					tags.push({
						text: '已报备',
						type: 'primary'
					})
				}

				if (customer.isRegistration === 1) {
					tags.push({
						text: '已到访',
						type: 'success'
					})
				}

				if (customer.bindCustomId) {
					tags.push({
						text: '已分配',
						type: 'success'
					})
				}

				if (customer.status === 'cancel') {
					tags.push({
						text: '无效客户',
						type: 'error'
					})
				}

				return tags
			},

			// 格式化手机号
			formatPhone(phone) {
				if (!phone) return ''
				return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
			},

			// 格式化时间
			formatTime(timestamp) {
				if (!timestamp) return ''
				const date = new Date(timestamp)
				const now = new Date()
				const diff = now - date
				const oneDay = 24 * 60 * 60 * 1000

				// 如果是今天，显示时间
				if (diff < oneDay && date.getDate() === now.getDate()) {
					return `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`
				}

				// 如果是今年，显示月日
				if (date.getFullYear() === now.getFullYear()) {
					return `${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
				}

				// 其他情况显示完整日期
				return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`
			},
			viewCustomer(item) {
				uni.navigateTo({
					url: "/pages/mid/detail?id=" + item._id
				})
			},
			showQrcode(item) {
				this.$refs.qrcode.open()
				setTimeout(() => {
					const qrcode = new UQRCode();
			
					console.log('嘻嘻嘻', qrcode)
					qrcode.data = item.scheduleNo;
					qrcode.size = 250;
					qrcode.margin = 15;
					qrcode.foregroundColor = '#000000';
					qrcode.backgroundColor = '#ffffff';
					qrcode.errorCorrectLevel = UQRCode.errorCorrectLevel.H;
					qrcode.make();
					const ctx = uni.createCanvasContext('myQrcode', this);
					qrcode.canvasContext = ctx;
					qrcode.draw();
				}, 100)
			},
			saveQRCode() {
				// 将canvas内容保存为图片
				uni.canvasToTempFilePath({
					canvasId: 'myQrcode',
					success: (res) => {
						// #ifdef H5
						const a = document.createElement('a');
						a.href = res.tempFilePath;
						a.download = 'qrcode.png'; // 设置下载文件名
						document.body.appendChild(a);
						a.click();
						document.body.removeChild(a);
						// #endif
						// #ifndef H5
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功',
									icon: 'success'
								});
							},
							fail: (err) => {
								console.error('保存失败', err);
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								});
							}
						});
						// #endif
					},
					fail() {
						console.log('fail')
					}
				}, this);
			}

		}
	}
</script>

<style scoped lang="scss">
	.customer-page {
		background-color: #f8f8f8;
	}

	/* 搜索区域 */
	.search-section {
		padding: 20rpx 30rpx;
		background: white;
		position: sticky;
		top: 0;
		z-index: 10;
	}

	/* 筛选区域 */
	.filter-section {
		background: white;
		padding: 20rpx 30rpx;
		display: flex;
		gap: 20rpx;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.filter-item {
		display: flex;
		align-items: center;
		padding: 16rpx 24rpx;
		background: #f8f9fa;
		border-radius: 12rpx;
		border: 1rpx solid #e9ecef;
		flex: 1;

		.filter-label {
			font-size: 26rpx;
			color: #495057;
			margin-right: 12rpx;
			white-space: nowrap;
		}

		.filter-value {
			font-size: 26rpx;
			color: #343a40;
			flex: 1;
		}
	}

	/* 选项卡区域 */
	.tab-section {
		background: white;
		border-bottom: 1rpx solid #f0f0f0;
	}

	.tab-scroll {
		white-space: nowrap;
		width: 100%;
	}

	.tab-container {
		display: inline-flex;
		padding: 0 30rpx;
	}

	.tab-item {
		padding: 24rpx 32rpx;
		position: relative;
		flex-shrink: 0;

		&.active {
			.tab-text {
				color: #007AFF;
				font-weight: 600;
			}
		}
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		transition: color 0.3s;
	}

	.tab-line {
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 60rpx;
		height: 4rpx;
		background: #007AFF;
		border-radius: 2rpx;
	}

	/* 内容区域 */

	.customer-list {
		height: 100%;
	}

	.list-container {
		padding: 20rpx 30rpx;
		min-height: 80%;
	}

	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 120rpx 0;

		.empty-image {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 40rpx;
			opacity: 0.6;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	/* 客户项 */
	.customer-item {
		background: white;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.06);

		&:last-child {
			margin-bottom: 0;
		}
	}

	.customer-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		margin-bottom: 20rpx;
	}

	.customer-name-phone {
		display: flex;
		flex-direction: column;
		gap: 8rpx;
	}

	.customer-name {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.customer-phone {
		font-size: 26rpx;
		color: #666;
	}

	.customer-time {
		font-size: 24rpx;
		color: #999;
		white-space: nowrap;
	}

	/* 状态标签 */
	.status-tags {
		display: flex;
		flex-wrap: wrap;
		margin-bottom: 20rpx;
		gap: 12rpx;
	}

	.status-tag {
		padding: 8rpx 16rpx;
		border-radius: 8rpx;
		font-size: 22rpx;
		font-weight: 500;

		&.primary {
			background: #e6f3ff;
			color: #007AFF;
		}

		&.success {
			background: #e6ffed;
			color: #52c41a;
		}

		&.error {
			background: #fff2f0;
			color: #ff4d4f;
		}
	}

	/* 项目信息 */
	.project-info {
		margin-bottom: 16rpx;

		.project-label {
			font-size: 26rpx;
			color: #999;
		}

		.project-name {
			font-size: 26rpx;
			color: #333;
			font-weight: 500;
		}
	}

	/* 备注信息 */
	.remark-section {
		margin-bottom: 16rpx;

		.remark-label {
			font-size: 26rpx;
			color: #999;
			margin-right: 8rpx;
		}

		.remark-text {
			font-size: 26rpx;
			color: #666;
			line-height: 1.50;
		}
	}

	/* 带看人信息 */
	.agent-info {
		display: flex;
		flex-wrap: wrap;
		align-items: center;
		gap: 16rpx;
		padding-top: 16rpx;
		border-top: 1rpx solid #f0f0f0;
		margin-top: 10rpx;
		.agent-label {
			font-size: 24rpx;
			color: #999;
		}

		.agent-name,
		.agent-phone,
		.agent-shop {
			font-size: 24rpx;
			color: #666;
			background: #f8f9fa;
			padding: 4rpx 12rpx;
			border-radius: 6rpx;
		}
	}

	/* 加载状态 */
	.load-status {
		padding: 30rpx 0;
	}

	.loading-more,
	.no-more {
		display: flex;
		justify-content: center;
	}

	/* 弹出层样式 */
	.popup-content {
		background: white;
		border-radius: 24rpx 24rpx 0 0;
		padding-bottom: env(safe-area-inset-bottom);
		max-height: 70vh;
	}

	.popup-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #eee;
		position: sticky;
		top: 0;
		background: white;
		z-index: 1;
	}

	.popup-title {
		font-size: 32rpx;
		font-weight: 600;
		color: #333;
	}

	.popup-close {
		font-size: 28rpx;
		color: #007AFF;
	}

	.popup-list {
		max-height: 50vh;
		overflow-y: auto;
	}

	.popup-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 24rpx 30rpx;
		border-bottom: 1rpx solid #f5f5f5;

		&.selected {
			background: #f8f9fa;
		}

		&:active {
			background: #f8f9fa;
		}
	}

	.popup-item-text {
		font-size: 28rpx;
		color: #333;
	}

	.btn-small {
		line-height: 60rpx;
		font-size: 30rpx;
		width: 200rpx;
		text-align: center;
		border-radius: 4rpx;
	}
	
	
	
	.qr-container {
		padding: 20rpx;
		text-align: center;
		background-color: white;
		border-radius: 8rpx;
	
		.qrcode-area {
			margin: 40rpx 0;
		}
	
		button {
			margin: 10rpx;
		}
		.btn-small2{
			padding: 10rpx 30rpx;
			border-radius: 4rpx;
			font-size: 30rpx;
			border: none;
			line-height: 40rpx;
			color: white;
		}
	}
	
	.action-buttons {
		display: flex;
		gap:10rpx;
		.btn-small {
			padding: 0 20rpx;
			border-radius: 4rpx;
			font-size: 22rpx;
			border: none;
			line-height: 40rpx;
			color: white;
			width: auto;
		
			&.primary {
				background: #667eea;
				color: white;
			}
		
			&.secondary {
				background: #f1f2f6;
				color: #666;
			}
		}
	}
</style>